package com.gp.billsrecord.ui.main.fragments

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import coil.ImageLoader
import coil.decode.SvgDecoder
import coil.load
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.gp.billsrecord.R
import com.gp.billsrecord.databinding.FragmentMainPersonalPreviewBinding
import com.gp.billsrecord.base.BaseFragment
import com.gp.billsrecord.base.Const
import com.gp.billsrecord.databinding.DialogAvatarSelectBinding
import com.gp.billsrecord.extensions.decodeUri
import com.gp.billsrecord.extensions.toMoney
import com.gp.billsrecord.model.data.LogonUser
import com.gp.billsrecord.model.datastore.ConstDataStore
import com.gp.billsrecord.vm.AppViewModel
import com.xujichang.base.extensions.click
import com.xujichang.base.extensions.postToast
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean

/*个人页面,总览*/
class PersonPreviewFragment : BaseFragment<FragmentMainPersonalPreviewBinding>() {
    private val svgImageLoader by lazy {
        ImageLoader.Builder(requireContext()).componentRegistry {
            add(SvgDecoder(requireContext()))
        }.build()
    }
    private val viewModel by viewModels<AppViewModel>()
    private val moneyShowing = AtomicBoolean(true)
    private val takePictureLauncher =
        //拍照后的逻辑
        registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
            it?.also {
                doUpdate(it)
            }
        }


    private val albumSelectLauncher =
        //选中相册后的返回数据的逻辑
        registerForActivityResult(ActivityResultContracts.GetContent()) {
            //选择相册中图片
            it?.also {
                doUpdate(BitmapFactory().decodeUri(requireContext(), it))
            }
        }

    private fun doUpdate(bitmap: Bitmap?) {
        bitmap?.also {
            viewModel.updateAvatar(it)
        } ?: postToast("图片数据获取失败")
    }

    override fun onBindingCreated() {
        //是否明码显示账户余额
        binding.btnHideMoney.click {
            moneyShowing.set(!moneyShowing.get())
            if (moneyShowing.get()) {
                //显示
                binding.tvUserBalance.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
                binding.btnHideMoney.setImageResource(R.drawable.ic_password_visible)
            } else {
                //隐藏
                binding.tvUserBalance.transformationMethod =
                    PasswordTransformationMethod.getInstance()
                binding.btnHideMoney.setImageResource(R.drawable.ic_password_unvisible)
            }
        }
        //点击头像
        binding.ivUserAvatar.click {
            //图片选择
            doPictureSelect()
        }
        //消费类型
        binding.tvConsumeTypeSetting.click {
            //消费类型设置

        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //监听用户信息
        viewModel.obtainLogonInfo().observe(viewLifecycleOwner) {
            //显示用户信息
            showUserInfo(it)
        }
        //获取所有账户信息
        viewModel.observeAccountList().observe(viewLifecycleOwner) { list ->
            var count = 0L
            list.forEach {
                count += it.balance
            }
            showAccountInfo(count)
        }
    }

    /**
     *显示账户余额
     */
    private fun showAccountInfo(count: Long) {
        binding.tvUserBalance.text = count.toMoney()
    }

    /**
     *  显示用户信息
     */
    private fun showUserInfo(user: LogonUser) {
        Log.i(TAG, "showUserInfo: ")
        //用户手机号
        binding.tvUserPhone.text = user.userPhone ?: "NONE"
        //用户名
        binding.tvUserName.text = user.userName
        //用户头像
        user.userAvatar?.let { File(it) }?.also {
            binding.ivUserAvatar.load(it) {
                crossfade(true)
            }
        } ?: binding.ivUserAvatar.load(R.drawable.ic_default_avatar, svgImageLoader) {
            crossfade(
                true
            )
        }
    }

    /**
     * 选取头像
     */
    private fun doPictureSelect() {
        val bottomSheetDialog = BottomSheetDialog(requireContext(), R.style.BottomSheet)
        val pictureSelectBinding = DialogAvatarSelectBinding.inflate(layoutInflater).apply {
            //退出
            tvExit.click {
                bottomSheetDialog.dismiss()
            }
            //相册
            tvPhotoAlbum.click {
                albumSelectLauncher.launch("image/*")
                bottomSheetDialog.dismiss()
            }
            //拍照
            tvTakePicture.click {
                takePictureLauncher.launch(null)
                bottomSheetDialog.dismiss()
            }
        }
        bottomSheetDialog.setContentView(pictureSelectBinding.root)
        bottomSheetDialog.show()
    }
}